import React, { useEffect, useState, useRef } from 'react'
import http from '../../api'
import { Toast } from 'antd-mobile'
import { useLocation, useNavigate } from 'react-router-dom'
import style from './index.module.css'
import { LoginType } from '../../myTypes'

export default function GetCode() {
  const location = useLocation()
  const navigate = useNavigate()
  const phone = location.state.phone as string
  const [time, setTime] = useState(60)
  const [code1, setCode1] = useState('')
  const [code2, setCode2] = useState('')
  const [code3, setCode3] = useState('')
  const [code4, setCode4] = useState('')
  // 给输入框绑定ref属性
  let inp1 = useRef<HTMLInputElement>(null)
  let inp2 = useRef<HTMLInputElement>(null)
  let inp3 = useRef<HTMLInputElement>(null)
  let inp4 = useRef<HTMLInputElement>(null)

  useEffect(() => {
    const timer = setInterval(() => {
      setTime((preTime) => {
        if (preTime > 0) {
          return preTime - 1
        } else {
          clearInterval(timer)
          return 60
        }
      })
    }, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [])

  async function sendCode() {
    const data = await http('post', '/mty/noteRandomCode/getLoginCode', { tel: phone })
    if (data && data.msg === '短信发送成功') {
      const timer = setInterval(() => {
        setTime((preTime) => {
          if (preTime > 0) {
            return preTime - 1
          } else {
            clearInterval(timer)
            return 60
          }
        })
      }, 1000)
      Toast.show({
        content: data.msg,
        position: 'top'
      })
    } else if (data) {
      Toast.show({
        content: data.msg,
        position: 'top'
      })
    }
  }

  async function Login() {
    const data = await http('post', '/mty/phoneLogin', { tel: phone, code: code1 + code2 + code3 + code4 })
    if (data) {
      const result = data.data as LoginType
      localStorage.setItem('userId', result.id)
      navigate('/home')
    }
  }

  useEffect(() => {
    if (code1 !== '') {
      inp2.current?.focus()
    } else {
      inp1.current?.focus()
    }
  }, [code1])
  useEffect(() => {
    if (code2 !== '') {
      inp3.current?.focus()
    }
  }, [code2])
  useEffect(() => {
    if (code3 !== '') {
      inp4.current?.focus()
    }
  }, [code3])
  useEffect(() => {
    if (code4 !== '') {
      Login()
    }
  }, [code4])

  function setInput(e: any, id: number) {
    if (!isNaN(parseInt(e.target.value)) || e.target.value === '') {
      switch (id) {
        case 1:
          setCode1(() => {
            return e.target.value
          })
          break
        case 2:
          setCode2(e.target.value)
          break
        case 3:
          setCode3(e.target.value)
          break
        case 4:
          setCode4(e.target.value)
          break
      }
    }
  }

  function setFocus(id: number) {
    switch (id) {
      case 2:
        if (code1 === '') {
          inp1.current?.focus()
        }
        break
      case 3:
        if (code1 === '') {
          inp1.current?.focus()
        } else if (code2 === '') {
          inp2.current?.focus()
        }
        break
      case 4:
        if (code1 === '') {
          inp1.current?.focus()
        } else if (code2 === '') {
          inp2.current?.focus()
        } else if (code3 === '') {
          inp3.current?.focus()
        }
        break
    }
  }

  function dealKeyUp(e: any, id: number) {
    if (e.keyCode === 8) {
      switch (id) {
        case 2:
          if (code2 === '') {
            inp1.current?.focus()
          }
          break
        case 3:
          if (code3 === '') {
            inp2.current?.focus()
          }
          break
        case 4:
          if (code4 === '') {
            inp3.current?.focus()
          }
          break
      }
    }
  }

  return (
    <div className={style['login-container']}>
      <div className={style.mask}>
        {/* 顶部导航 */}
        <div className={style.nav}>
          <img src="/static/arrow/icon-arrow-right-fff.png" alt="" onClick={() => navigate(-1)} />
        </div>
        {/* 标题提示 */}
        <div className={style.tip}>
          <div className={style.title}>请输入验证码</div>
          <div className={style['tip-text']}>
            验证码已通过短信发送至+86
            <span className={style.phone}>{phone}</span>
          </div>
        </div>
        {/* 验证码输入框 */}
        <div className={style['code-inputs']}>
          <div className={style['code-input']}>
            <input ref={inp1} type="text" maxLength={1} onBlur={() => code1 === '' && inp1.current?.focus()} value={code1} onInput={(e) => setInput(e, 1)} />
          </div>
          <div className={style['code-input']}>
            <input ref={inp2} type="text" maxLength={1} value={code2} onKeyUp={(e) => dealKeyUp(e, 2)} onInput={(e) => setInput(e, 2)} onFocus={() => setFocus(2)} />
          </div>
          <div className={style['code-input']}>
            <input ref={inp3} type="text" maxLength={1} value={code3} onKeyUp={(e) => dealKeyUp(e, 3)} onInput={(e) => setInput(e, 3)} onFocus={() => setFocus(3)} />
          </div>

          <div className={style['code-input']}>
            <input ref={inp4} type="text" maxLength={1} value={code4} onKeyUp={(e) => dealKeyUp(e, 4)} onInput={(e) => setInput(e, 4)} onFocus={() => setFocus(4)} />
          </div>
        </div>
        {/* 时间计算 */}
        <div className={style['time']}>
          {time !== 60 && <div>{time}s</div>}
          {time === 60 && (
            <div className={style['reset-code']} onClick={sendCode}>
              重新发送
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
